#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

#define PORT 8888
// #define IP "8.138.248.21"
#define IP "0.0.0.0"


int i = 0;
struct sockaddr_in client_addr[10];

void *server(void *arg)
{
    int connfd = *(int *)arg;
    int index = i;
    printf("Client ip:%s, port:%d\n", inet_ntoa(client_addr[index].sin_addr), ntohs(client_addr[index].sin_port));

    while (1)
    {
        // 接收数据
        char buf[1024];
        ssize_t recv_res = recv(connfd, buf, sizeof(buf), 0);
        if (recv_res < 0)
        {
            perror("recv");
            continue;
        }
        if (recv_res == 0)
        {
            printf("客户端断开连接\n");
            close(connfd);
            break;
        }
        printf("客户端[%d]发送的数据：%s\n", index, buf);
    }
    close(connfd);
    printf("客户端[%d]断开连接\n", index);
}

int main()
{
    int socketfd = socket(AF_INET, SOCK_STREAM, 0); // 0 表示使用默认协议

    // 创建地址结构体
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    addr.sin_family = AF_INET;            // 使用IPv4
    addr.sin_port = htons(PORT);          // 端口号 8888
    addr.sin_addr.s_addr = inet_addr(IP); // inet_addr 将点分十进制IP地址转换为网络字节序

    // 绑定
    bind(socketfd, (struct sockaddr *)&addr, sizeof(addr));

    // 监听
    listen(socketfd, 10); // 10 表示最大连接数
    printf("监听中...\n");

    pthread_t tid[10];
    int connfd[10] = {0};

    while (1)
    {
        printf("waiting....\n");

        memset(&client_addr[i], 0, sizeof(client_addr[i]));

        // 等待客户端连接
        int ClientAddr_len = sizeof(client_addr[i]);
        connfd[i] = accept(socketfd, (struct sockaddr *)&client_addr[i], &ClientAddr_len);
        if (connfd[i] < 0)
        {
            perror("accept");
            continue;
        }
        // pthread_detach(tid[i]);
        pthread_create(&tid[i], NULL, server, (void *)&connfd[i]);
        i++;
    }

    close(socketfd);
    return 0;
}